/**
 * Created by jianglinjie on Thu Sep 21 2017
 * @flow
 */
'use strict';
import _createError from 'http-errors';
import { ErrorCode } from '../constants';
import { createErrorBody } from './BodyUtils';
import { logger } from './LoggerUtils';
import { GlobalDefines } from '../constants';

export function createError(status: number, message: string, code: string): Error {
  let error = _createError(status, message, { [GlobalDefines.CUSTOM_ERROR_CODE_KEY]: code });
  return error; 
}

export let errorMiddleware = async (ctx: Object, next: Function) => {
  try {
    await next();
  } catch (err) {
    if (err[GlobalDefines.CUSTOM_ERROR_CODE_KEY]) {
      ctx.response.status = err.status || 500;
      ctx.response.body = createErrorBody(err[GlobalDefines.CUSTOM_ERROR_CODE_KEY], err.message);        
    } else {
      ctx.response.status = err.statusCode || err.status || 500;  
      ctx.response.body = createErrorBody(ErrorCode.COMMON_ERROR, err.message);                
    }

    ctx.app.emit('error', err, ctx);

    logger.error('%s %s err: ', ctx.method, ctx.originalUrl, err)
  }
};

export function isMongoDuplicateKeyError(err: any): boolean {
  return err.name === 'MongoError' && err.code === 11000;
}

